var express = require('express');
var router = express.Router();
//导入中间件
const checkLoginMiddleware = require('../../middlewares/checkLoginMiddleware')

//导入lowdb
// const low = require('lowdb')
// const FileSync = require('lowdb/adapters/FileSync');
// const adapter = new FileSync(__dirname + '/../data/db.json');
//导入shortid
// const shortid = require('shortid');


//导入moment
const moment = require('moment');
const AccountModel = require('../../models/AccountModel');
// console.log(moment('2023-11-14').toDate());
//获取db对象
// const db = low(adapter)

//添加首页路由规则
router.get('/',(req,res)=>{
  //重定向
  res.redirect('/account');
})

//记账本列表
router.get('/account', checkLoginMiddleware,function(req, res, next) {
  //let accounts = db.get('accounts').value();
  //读取集合信息
  AccountModel.find().sort({time: -1}).exec().then((data) => {
    // 响应成功的提示
    res.render('list', { accounts: data, moment: moment });
  }).catch((err) => {
    // 处理错误
    res.status(500).send('读取失败~~~');
  });

});

//添加记录
router.get('/account/create', checkLoginMiddleware,function(req, res, next) {
  res.render('create')
});

//新增记录
router.post('/account',checkLoginMiddleware,(req,res)=>{
  //生成id
  //let id = shortid.generate();
  //写入文件
  //db.get('accounts').unshift({id:id,...req.body}).write();
  //成功提醒
  //插入数据
  AccountModel.create({
    ...req.body,
    //修改time属性
    time: moment(req.body.time).toDate()
  }).then((data)=>{
    res.render('success',{msg: '添加成功！',url: '/account'})
  }).catch(()=>{
    res.status(500).send('插入失败~')
    return;
  })
})

//删除记录
router.get('/account/:id',checkLoginMiddleware,(req,res)=>{
  //获取params的id参数
  let id = req.params.id;
  //删除
  // db.get('accounts').remove({id:id}).write();
  AccountModel.deleteOne({_id: id}).then((data)=>{
    //提醒
    res.render('success',{msg: '删除成功！',url: '/account'})
  }).catch((err)=>{
    res.status(500).send('删除失败~');
  })

})

module.exports = router;
